package heap;

import java.util.*;

/**
 * @author pengfei.hpf
 * @date 2020/3/1
 * @verdion 1.0.0
 */
public class TwitterII {

    int timestamp = 0;
    Map<Integer, Twitt> userTwitt;
    Map<Integer, Set<Integer>> followMap;
    /** Initialize your data structure here. */
    public TwitterII() {
        userTwitt = new HashMap<>();
        followMap = new HashMap<>();
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
         Twitt t = userTwitt.get(userId);
         Twitt newT = new Twitt(tweetId, timestamp);
         timestamp ++;
         newT.next = t;
         userTwitt.put(userId, newT);
    }

    /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
    public List<Integer> getNewsFeed(int userId) {
        Set<Integer> set = followMap.get(userId);
        if(set == null){
            set = new HashSet<>();
            set.add(userId);
            followMap.put(userId, set);
        }
        List<Twitt> lists = new LinkedList<>();
        for(Integer u: set){
            Twitt t = userTwitt.get(u);
            if(t != null){
                lists.add(t);
            }
        }
        PriorityQueue<Twitt> queue = new PriorityQueue<>((t1,t2)->(t2.time - t1.time));
        queue.addAll(lists);
        int index = 0;
        List<Integer> res = new LinkedList<>();
        while(index < 10 && !queue.isEmpty()){
            Twitt t= queue.poll();
            res.add(t.id);
            if(t.next != null){
                queue.add(t.next);
            }
            index ++;
        }
        return res;
     }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        Set<Integer> set = followMap.get(followerId);
        if(set == null){
            set = new HashSet<>();
            set.add(followerId);
            followMap.put(followerId, set);
        }
        set.add(followeeId);
    }

    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
          if(followeeId != followerId){
              Set<Integer> set = followMap.get(followerId);
              if(set != null){
                  set.remove(followeeId);
              }
          }
    }

    class Twitt{
        int time;
        int id;
        Twitt next;
        Twitt(int i, int t){
            id = i;
            time = t;
        }
    }
}
